<template>
  <div class="fillcontain">
    <div class="head-title"><i class="el-icon-edit-outline">决策表</i></div>

    <el-form
      :model="dataForm"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
      class="form-container"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="规则组标识"
            label-width="120px"
            prop="groupIdentify"
          >
            <el-input
              v-model="dataForm.groupIdentify"
              placeholder="规则组标识"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则组名称" label-width="120px" prop="groupName">
            <el-input
              v-model="dataForm.groupName"
              placeholder="规则组名称"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="mb10 pl20">
      <div class="content-title"><span>决策表</span></div>

      <el-row class="mb10">
        <el-col :span="16">
          <el-button type="info" plain @click="addDecisionRow()">新增行</el-button>
          <el-button type="info" plain @click="addConditionCol('1')"
            >新增条件列</el-button
          >
          <el-button type="info" plain @click="addConditionCol('2')"
            >新增动作列</el-button
          >
          <el-button type="info" plain @click="clearData()">清空表数据</el-button>
          <el-button type="info" plain @click="clearHead()">清空表头</el-button>
        </el-col>
      </el-row>
    </div>

    <div class="contain">
      <!-- 列表 -->
      <el-table :data="tableDatas" style="width: 100%">
        <el-table-column
          v-for="(col, i) in conditionList"
          :property="col.decisionCode"
          :key="col.decisionCode"
          :index="i"
          :label="col.conditionDesc"
        >
          <template slot="header" slot-scope="scope">
            <span v-if="conditionList[scope.column.index].headType == '1'"
              >{{ scope.column.label }} (条件)</span
            >
            <span v-if="conditionList[scope.column.index].headType == '2'"
              >{{ scope.column.label }} (动作)</span
            >
            <!--            <span @mouseup="edit(scope)">X</span>-->
          </template>
          <template slot-scope="scope">
            <el-input
              v-model="scope.row[scope.column.property].conditionDesc"
              readOnly
              placeholder="请输入"
              @click.native="editDecision(scope, scope.$index)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="delDecision(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="content-footer">
      <el-button type="info" plain @click="dataFormSubmit()">确定</el-button>
      <el-button @click="toList">取消</el-button>
    </div>

    <!-- 弹窗, 表头 -->
    <add-decision-head
      v-if="addConditionVisible"
      ref="addCondition"
      :entityList="entityList"
      :chooseIndex="chooseIndex"
      :conditionList="conditionList"
      @refreshDataList="getConditionDataList"
    ></add-decision-head>
    <!-- 弹窗, 表头 -->
    <edit-decision-value
      v-if="editConditionVisible"
      ref="editCondition"
      :entityList="entityList"
      :chooseIndex="colIndex"
      :conditionList="conditionList"
      @refreshDataList="getConditionData"
    ></edit-decision-value>
  </div>
</template>

<script>
import { getData } from "@/api/ruleConfig/branchGroupInfo";
import { entityList } from "@/api/baseConfig/entity";
import {
  saveDecisions,
  getDecisionsByGroup,
} from "@/api/ruleConfig/branchDecision";
import addDecisionHead from "./add-decision-head";
import editDecisionValue from "./edit-decision-value";
import constant from "@/api/constant";

export default {
  data() {
    return {
      rowIndex: null, //行索引
      colIndex: null, //列索引
      condition: [], //当前表头信息
      delList: [], //当前表头信息
      delHeadList: [], //当前表头信息
      editConditionVisible: false,
      entityList: [],
      conditionList: [], //表头信息
      chooseIndex: 0,
      addConditionVisible: false,
      tableDatas: [], //决策表数据
      groupTypes: constant.ruleConfig.groupTypes,
      addOrUpdateVisible: false,
      checkEntity: [],
      dataList: [],
      isDisabled: false,
      visible: false,
      dataForm: {
        id: null,
        groupName: "",
        groupDesc: "",
        groupIdentify: "",
        groupBranchCode: "",
        remark: "",
        groupType: "1",
        isEffect: "1",
      },
      entitysProperties: [],
      dataRule: {},
    };
  },
  created() {},
  components: {
    addDecisionHead,
    editDecisionValue,
  },
  mounted() {
    let id = this.$route.params.id;
    this.init(id);
  },
  methods: {
    delDecision(data) {
      this.$confirm(`确定进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableDatas.splice(data.row, 1);
          let row = data.row;
          this.conditionList.forEach((item) => {
            if (row[item.decisionCode].id) {
              this.delList.push(row[item.decisionCode]);
            }
          });
          // console.log(this.delList);
        })
        .catch(() => {});
    },
    clearHead() {
      if (this.tableDatas.length > 0) {
        this.$message.error("有关联表格数据,不能删除表头");
        return;
      }
      this.$confirm(`确定进行[清楚]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.conditionList.forEach((item) => {
            if (item.id) {
              this.delHeadList.push(item);
            }
          });
          this.conditionList = [];
          // console.log(this.delHeadList);
        })
        .catch(() => {});
    },
    clearData() {
      this.$confirm(`确定进行[清除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableDatas.forEach((row) => {
            this.conditionList.forEach((item) => {
              if (row[item.decisionCode].id) {
                this.delList.push(row[item.decisionCode]);
              }
            });
          });

          this.tableDatas = [];
          // console.log(this.delList);
        })
        .catch(() => {});
    },

    // 刷新表值
    getConditionData(data) {
      // console.log(data);
      let newData = [];
      this.tableDatas.forEach((item, index) => {
        if (index == this.rowIndex) {
          item[data.decisionCode] = JSON.parse(JSON.stringify(data));
        }
        newData.push(item);
      });
      this.tableDatas = newData;
      // console.log(this.tableDatas);
    },
    // 修改决策表值
    editDecision(data, index) {
      // console.log(data);
      this.rowIndex = index;
      this.colIndex = data.column.index;
      this.editConditionVisible = true;
      let col = this.conditionList[this.colIndex];
      let colData = this.tableDatas[this.rowIndex][col.decisionCode];
      this.$nextTick(() => {
        this.$refs.editCondition.init(JSON.stringify(colData));
      });
    },
    //新增一行决策表值
    addDecisionRow() {
      if (this.conditionList.length <= 0) {
        this.$message.error("请添加表头信息");
        return;
      }
      let params = {};
      this.conditionList.forEach((item) => {
        params[item.decisionCode] = {
          conditionType: "",
          decisionCode: item.decisionCode,
          divisorId: null,
          leftProperty: null,
          rightProperty: null,
          leftEntityId: null,
          rightEntityId: null,
          sysbol: "",
          rightValue: "",
          decisionExp: "",
          conditionExpression: "",
          conditionDesc: "",
          conditionMethodType: "",
          methodParams: "",
          methodName: "",
          remark: "",
        };
      });
      this.tableDatas.push(params);
      // console.log(this.tableDatas);
    },
    //刷新决策表头列表
    getConditionDataList(data) {
      if (this.chooseIndex != null) {
        this.conditionList[this.chooseIndex] = data;
      } else {
        if (this.conditionList.length > 0) {
          let flag = false;
          this.conditionList.forEach((item) => {
            if (item.conditionExpression === data.conditionExpression) {
              flag = true;
            }
          });
          if (flag) {
            this.$message.error("已存在相同表头信息，请重新添加");
            return;
          }
          let code =
            this.conditionList[this.conditionList.length - 1].decisionCode;
          code = Number(code.replace("D000", ""));
          data.decisionCode = "D000" + Number(code + 1);
        } else {
          data.decisionCode = "D000" + Number(this.conditionList.length + 1);
        }
        this.conditionList.push(data);
      }
      // console.log(this.tableDatas);
      // 已经新增的行 添加列
      if (this.tableDatas.length > 0) {
        this.tableDatas.forEach((item, index) => {
          item[data.decisionCode] = {
            conditionType: "",
            divisorId: null,
            leftProperty: null,
            rightProperty: null,
            leftEntityId: null,
            rightEntityId: null,
            sysbol: "",
            rightValue: "",
            decisionExp: "",
            conditionExpression: "",
            conditionDesc: "",
            conditionMethodType: "",
            methodParams: "",
            methodName: "",
            remark: "",
          };
          item[data.decisionCode] = JSON.parse(JSON.stringify(data));
          item[data.decisionCode].conditionDesc = null;
        });
      }

      // console.log(this.tableDatas);
    },

    //1-添加决策表条件列 2-添加决策表动作列
    addConditionCol(type) {
      if (this.checkEntity.length <= 0) {
        this.$message.error("请关联实体");
        return;
      }
      this.entityList = [];
      this.chooseIndex = null;
      this.checkEntity.forEach((item) => {
        this.entitysProperties.forEach((e) => {
          if (item === e.entityId + "") {
            let entity = {
              entityName: e.entityName,
              entityIdentify: e.entityIdentify,
              entityId: e.entityId,
              pkgName: e.pkgName,
            };
            this.entityList.push(entity);
          }
        });
      });
      this.addConditionVisible = true;
      this.$nextTick(() => {
        this.$refs.addCondition.init(type);
      });
    },

    changeGroupType(data) {},

    toList() {
      constant.clearTag(this);
      this.$router.push({
        path: "/drools-ruleConfig/branch/add-or-update/" + this.dataForm.id,
      });
    },

    //初始化规则组信息
    init(id) {
      // console.log(id);
      this.visible = true;
      this.isDisabled = false;
      this.entitysProperties = [];
      this.checkEntity = [];

      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.getEntityProperties();

        if (id && id != "undefined") {
          this.dataForm.id = id;
          this.isDisabled = true;
          let params = {
            id: this.dataForm.id + "",
          };
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          getData(params)
            .then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.data.data && res.data.resultCode === 0) {
                this.dataForm = res.data.data.groupInfo;
                res.data.data.relList.forEach((item) => {
                  this.checkEntity.push(item.entityId + "");
                });
                this.initDecision();
              }
            })
            .catch((err) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
            });
        }
      });
    },

    //初始化规则组下已有决策表信息
    initDecision() {
      let params = {
        groupIdentify: this.dataForm.groupIdentify,
        branchCode: this.dataForm.groupBranchCode,
      };
      if (localStorage.getItem("checktaskobj")) {
        let checktaskobj = JSON.parse(localStorage.getItem("checktaskobj"));
        params.taskNo = checktaskobj.taskNo;
      }
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      getDecisionsByGroup(params)
        .then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.data.data) {
            this.tableDatas = res.data.data.body;
            this.conditionList = res.data.data.head;
          }
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
    },

    // 获取实体类的属性
    getEntityProperties() {
      entityList({}).then((res) => {
        if (res.data.data) {
          this.entitysProperties = [];
          res.data.data.forEach((item) => {
            item["label"] = item.entityIdentify + " -- " + item.entityName;
            this.entitysProperties.push(item);
          });
        }
      });
    },

    // 表单提交
    dataFormSubmit() {
      // console.log(this.checkEntity);

      let values = [];
      if (this.tableDatas.length > 0) {
        for (var i = 0; i < this.tableDatas.length; i++) {
          let data = this.tableDatas[i];

          this.conditionList.forEach((item) => {
            data[item.decisionCode]["rowIndex"] = i;
            values.push(data[item.decisionCode]);
          });
        }
      }
      // console.log(values);

      let params = {
        groupIdentify: this.dataForm.groupIdentify,
        branchCode: this.dataForm.groupBranchCode,
        heads: JSON.stringify(this.conditionList),
        values: JSON.stringify(values),
        delList: JSON.stringify(this.delList),
        delHeadList: JSON.stringify(this.delHeadList),
      };
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      saveDecisions(params)
        .then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.data && res.data.resultCode === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.visible = false;

                // this.$emit('refreshDataList')
                this.toList();
              },
            });
          } else {
            this.$message.error(res.data.resultMsg);
          }
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
    },
  },
  filters: {},
};
</script>

<style lang="scss">
.el-table__row .el-form-item__content {
  margin-left: 0 !important;
}

.el-table__row .el-form-item {
  margin-bottom: 0 !important;
}
</style>
